﻿package {
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	
	import idv.cjcat.display.LineStyle;
	import idv.cjcat.display.dynashape.DynaGraphics;
	import idv.cjcat.display.dynashape.DynaShape;
	import idv.cjcat.display.shapes.Circle;
	import idv.cjcat.physics.fenozix.Fenozix;
	
	public class Main extends Sprite {
		
		private var circles:Array;
		private var ds:DynaShape;
		private var engine:Fenozix;
		
		public function Main():void {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			circles = new Array();
			var i:int;
			for (i = 0; i < 5; i++) {
				var c:Circle = new Circle(10);
				c.y = 20 * i;
				circles.push(c);
				addChild(c);
			}
			
			//Creates the simulation environment
			engine = new Fenozix();
			engine.gravity.y = 0.5;
			engine.add(circles[0], 0); //static object
			for (i = 1; i < circles.length; i++) engine.add(circles[i]);
			for (i = 0; i < circles.length - 1; i++) engine.createSpring(circles[i], circles[i + 1], 0.05, 50);
			engine.iterations = 10;
			
			//Creates a DynaShape for spring constarints visualization
			ds = new DynaShape();
			var dg:DynaGraphics = new DynaGraphics();
			dg.lineStyle(new LineStyle());
			dg.moveTo(circles[0]);
			for (i = 1; i < circles.length; i++) dg.lineTo(circles[i]);
			ds.add(dg);
			addChildAt(ds, 0);
			
			//The main loop
			addEventListener(Event.ENTER_FRAME, loop);
			
		}
		
		private function loop(e:Event):void {
			circles[0].x = mouseX;
			circles[0].y = mouseY;
			engine.step();
			ds.render();
		}
		
	}
	
}